import app from '@system.app'
import UNION_AD_SDK from 'union-quick-app-ad/app.js'
import YLHQuickAppSDK from 'ylh-quick-app-ad-sdk/pure'
var adConfigData = {
  adInitFailconut: 0,//广告sdk重新初始化次数
  advConfig: null, //广告配置
  adClickBetweenTimes: 2000, //广告请求间隔预设值 ms
  adRequestTimesTemp: 0, //广告请求时间戳标记 timestamp
  isShowToast: false,
  materialType: 1, //素材和icon优先级
  uploadFristPopClick: 0, // 0未上报 3已切换页面 2已上报
}
function updataAdConfigData(obj) {
  try {
    Object.assign(adConfigData, obj)
    LOG(
      'AD',
      `广告ADSDKUTILS========>updataAdConfigData数据更新完成`,
      adConfigData,
      obj
    )
  } catch (error) {
    LOG('AD', `广告ADSDKUTILS========>updataAdConfigData数据更新失败`, error)
  }
}
/**
 * 获取广告
 * @param {Object} param
 * @returns
 */
function getAd(param) {
  let {
    scenario,
    sceneCode,
    adType,
    adTimes,
    popName,
    popGroupName,
    requestNum,
    indexBoost,
    scene,
    isBidding,
    bannerTurn,
    preDeleteStatus,
    index,
    adTypes,
  } = param
  if (adTimes >= 2) {
    LOG('AD', `广告ADSDKUTILS========>请求轮询完毕`, param)
    return param && param.fail && param.fail(param)
  }

  if (adType == 5) {
    LOG('AD', `广告ADSDKUTILS========>请求间隔限制toast提示`, param)
    return (
      param &&
      param.fail &&
      param.fail({
        message: '没有获取到广告',
        code: 1,
      })
    )
  }

  // 获取广告类型
  let adInfo = getAdType(param)
  if (!adInfo) {
    LOG('AD', `广告ADSDKUTILS========>场景配置关闭`, param)
    return param && param.fail && param.fail('没有获取到广告')
  }
  if (adInfo.adType == 3 && !adInfo.bqtTempId) {
    LOG('AD', `广告ADSDKUTILS========>命中百度广告，且无百度配置`, adInfo)
    param.adTimes++
    param.adType = 1
    return getAd(param)
  }
  param.adType =
    param && param.adType && param.adType != 4 ? param.adType : adInfo.adType

  // 请求间隔判定
  let checkRes = checkRequestInterval(param)
  if (param.adType !== 3 && checkRes) {
    //原生广告请求判断 广告请求间隔下预设值  请求百度广告
    if (checkRes == 1) {
      //不触发
      LOG('AD', `广告ADSDKUTILS========>命中请求间隔,不触发`)
      param.adTimes = 2
      return getAd(param)
    } else if (checkRes == 2) {
      // 按照优先级继续请求
      LOG('AD', `广告ADSDKUTILS========>命中请求间隔,按照优先级继续请求`)
      param.adTimes++
      param.adType = 3
      return getAd(param)
    } else if (checkRes == 3) {
      // toast提示
      if (!adConfigData.isShowToast) {
        LOG('AD', `广告ADSDKUTILS========>命中请求间隔,Toas提示`)
        adConfigData.isShowToast = true
        //如果已经提示过用户 500m内再次触发则不toast 防止一个弹窗同时发起多次请求，导致多次toast的问题
        setTimeout(() => {
          adConfigData.isShowToast = false
        }, 500)
        require('@system.prompt').showToast({
          message: '操作太快了请重试!',
        })
      }
      param.adType = 5
      return getAd(param)
    }
    return
  }

  AD_SDK.getManuAdv({
    scenario,
    sceneCode,
    popName,
    popGroupName,
    requestNum,
    indexBoost,
    scene,
    isBidding,
    bannerTurn,
    adType: param.adType,
    adTimes: param.adTimes,
    bqtTempId: adInfo.bqtTempId,
    preDeleteStatus,
    index,
    adTypes,
    success: function (res) {
      param && param.success && param.success(res)
    },
    fail: function (adType) {
      if (adType == 1 || adType == 2) {
        // 原生失败 获取百度
        param.adTimes++
        param.adType = 3
        getAd(param)
      } else {
        // 百度失败 获取原生
        param.adTimes++
        param.adType = 1
        getAd(param)
      }
    },
  })
}
/**
 * 获取当前广告类型
 * @param {String} sceneCode 场景code
 * @returns 1->原生  3-> 百度
 */
function getAdType(param) {
  LOG('AD', '广告ADSDKUTILS=>getAdType1', adConfigData.advConfig)
  LOG('AD', '广告ADSDKUTILS=>getAdType2', JSON.parse(JSON.stringify(param)))

  let { sceneCode, adType } = param
  if (adConfigData.advConfig.scene_switch_list) {
    let result = adConfigData.advConfig.scene_switch_list.filter(
      (res) => res.scene_code == sceneCode && res.status
    )
    if (result.length > 0) {
      let item = result[0]
      if (
        adType == 0 &&
        item.baidu_ad_priority &&
        item.native_ad_priority < item.baidu_ad_priority
      ) {
        return {
          adType: 3,
          bqtTempId: item.baidu_ad_template,
        }
      }
      if (adType == 3) {
        return {
          adType: 3,
          bqtTempId: item.baidu_ad_priority ? item.baidu_ad_template : '',
        }
      }
      return {
        adType: 1,
        bqtTempId: '',
      }
    }
  }

  if (adConfigData.advConfig.popup_switch_list) {
    let result = adConfigData.advConfig.popup_switch_list.filter(
      (res) => res.scene_code == sceneCode
    )
    if (result.length > 0) {
      let item = result[0]
      LOG('AD', '广告ADSDKUTILS=>getAdType4', item)
      if (
        adType == 0 &&
        item.baidu_ad_priority &&
        item.app_ad_priority < item.baidu_ad_priority
      ) {
        return {
          adType: 3,
          bqtTempId: '3002',
        }
      }
      if (adType == 3) {
        return {
          adType: 3,
          bqtTempId: item.baidu_ad_priority ? '3002' : '',
        }
      }
      return {
        adType: 1,
        bqtTempId: '',
      }
    }
  }
  return null
}

/**
 * 请求间隔判定
 * @param {Object} param
 * @returns 0-> 自定义/返回弹窗不触发 1-> 自定义、返回弹窗按顺序请求其他广告 2-> toast提示逻辑
 */
function checkRequestInterval(param) {
  let { sceneCode } = param
  let res = 0
  if (
    adConfigData.adRequestTimesTemp == 0 ||
    adConfigData.advConfig.ad_request_config == []
  )
    return res
  if (
    adConfigData.adRequestTimesTemp +
    adConfigData.advConfig.ad_request_config.interval_time >
    new Date().getTime()
  ) {
    if (sceneCode == 'AD_POP_CUSTOM') {
      // 若果是自定义弹窗
      //    return adConfigData.advConfig.ad_request_config.interval_custom_popup_type ? 1 : 2
      res = adConfigData.advConfig.ad_request_config.interval_custom_popup_type
    }
    if (sceneCode.indexOf('BACK') != -1) {
      // 如果是自定义返回
      res = adConfigData.advConfig.ad_request_config.interval_back_popup_type
    }
    LOG('AD', '广告ADSDKUTILS=>checkRequestInterval 请求间隔命中', res)
  }
  LOG('AD', '广告ADSDKUTILS=>checkIsGetBqtAd', false)
  return res
}

/**
 *
 * @param {String} action 触发请求间隔动作 adRequest-> 广告请求 adClick-> 广告点击
 */
function markAdRequestInterval(action, obj) {
  LOG(
    'AD',
    '广告ADSDKUTILS=>markAdRequestInterval===========>',
    action,
    obj,
    adConfigData.uploadFristPopClick
  )
  if (
    adConfigData.uploadFristPopClick == 1 && obj.sceneCode &&
    obj.sceneCode.indexOf('POP') != -1
  ) {
    adConfigData.uploadFristPopClick = 2
  }
}

function clickManuAdvForBtn(adObj, clickType = 'btn') {
  // 标记点击 用于间隔判断
  markAdRequestInterval('adClick', adObj)
  if (adObj.type == 'manu_ad') {
    POP_TOOLS.setIntervalAttr()
  }

  AD_SDK.clickManuAdvForBtn(adObj, clickType)
}

function clickManuAdvForImg(adObj, clickType = 'img') {
  // 标记点击 用于间隔判断
  markAdRequestInterval('adClick', adObj)
  if (adObj.type == 'manu_ad') {
    POP_TOOLS.setIntervalAttr()
  }
  AD_SDK.clickManuAdvForImg(adObj, clickType)
}
/**
 * 广告初始化
 * @param {Object} params ad_sdk所需的参数
 * @returns
 */
function initSdk(params) {
  return AD_SDK.initSdk(params)
}

/**
* 初始化广告sdk
* @param {String} pageUrl 页面名称
* @param {Object} obj app.ux 内 $app 数据
* @param {BOOL} isCheckStatus 是否强制重新初始化
* @param {Function} callBack 1 初始化成功  2 初始化失败
*/
const initAdInfo = async (callBack) => {
  let _app = GLOBAL_UTILS.global_data._APP
  // 判断全局配置是否存在,不存在则请求
  let adNewPostionConfig = await TACTICS_SDK.getNewAdPostionInfo()
  LOG('广告配置请求成功===>', adNewPostionConfig)
  let nowTime = new Date().getTime()
  $utils.setStorage('UNION_AD_CACHE', {
    hasAuthored: { expire_time: nowTime - nowTime % 864e5 + 864e5 - 288e5, val: true }
  })
  try {
    // 初始化ylh_sdk
    if (!_app.ylh_sdk && adNewPostionConfig && adNewPostionConfig.ad_protogenesis) {
      adNewPostionConfig.ad_protogenesis.forEach(item => {
        if (item.ad_type == 2) {
          new YLHQuickAppSDK(GLOBAL_UTILS.global_data._THIS.$app, { appId: item.product_id })
        }
      })
    }
  } catch (error) { }
  //防止存入storage慢
  setTimeout(() => {
    new UNION_AD_SDK(GLOBAL_UTILS.global_data._THIS.$app)
  }, 50)

  // 广告场景配置
  let adSdkUtilsConfig = TACTICS_SDK.getQdConfig('ad_config')
  let bqtAdConfig = TACTICS_SDK.getBqtAdConfigInfo()
  let ad_btn_text_type = Number(TACTICS_SDK.getGlobalData('configInfo')['config']['ad_btn_text_type'].val)
  let is_bqt_can_show_dialog = Number(TACTICS_SDK.getGlobalData('configInfo')['config']['is_bqt_can_show_dialog'].val)
  AD_SDK_UTILS.updataAdConfigData({
    advConfig: adSdkUtilsConfig,
    materialType: ad_btn_text_type
  })

  let { deviceInfo, android, channelId, manifest, linkId, utm_ad_id, utm_source, utm_content } = _app
  let appInfo = app.getInfo()
  initSdk({
    isCheckStatus: true, //是否需要强制初始化sdk
    deviceInfo, //设备信息
    android, //安卓id
    qudao: channelId,//渠道id
    adPlanId: utm_ad_id,// 计划id
    link_id: linkId,//链接id
    pageUrl: GLOBAL_UTILS.global_data._THIS.pageDetail.pageName,//页面来源
    sourcePkg: appInfo.source.packageName ? appInfo.source.packageName : 'noSourcePackage',//来源包名
    unionid: utm_source, // 媒体id
    utm_content, //创意id
    vivoChannelFilter: adSdkUtilsConfig.vivo ? adSdkUtilsConfig.vivo : '', //vivo渠道上报
    materialType: ad_btn_text_type, //icon和素材优先
    adNewPostionConfig: Object.assign({}, adNewPostionConfig, bqtAdConfig), //新的广告配置
    isBqtCanShowDialog: is_bqt_can_show_dialog,
    success: function () {
      LOG('SDK初始化成功')
      callBack(1)
    },
    fail: function () {
      adConfigData.adInitFailconut++
      if (adConfigData.adInitFailconut == 3) {
        adConfigData.adInitFailconut = 0
        LOG("广告初始化3次失败！")
        callBack(2)
        return
      }
      initAdInfo(callBack)
    }
  })
}
export default {
  adConfigData,
  updataAdConfigData, //初始化参数
  getAd, // 获取广告
  markAdRequestInterval, //间隔标记
  clickManuAdvForBtn, //点击按钮
  clickManuAdvForImg, //点击素材
  initAdInfo
}
